﻿using GmailChecker.Utils;
using System;
using System.Windows.Forms;

namespace GmailChecker.Forms
{
    public partial class AppForm : Form
    {                
        public AppForm()
        {            
            InitializeComponent();                                                    
        }        

        private void AppFormLoad(object sender, EventArgs e)
        {                        
            InitForm();
            AddEvents();

            MailBoxTimer.AddEvent(timer);
            MailBoxTimer.Init(timer);
        }

        private void InitForm()
        {                        
            notifyIcon.Visible = true;
            Hide();

            MailBox.Email = emailTextBox.Text = AppSettings.Email;
            MailBox.Password = passwordTextBox.Text = AppSettings.Password;           
        }

        private void AddEvents()
        {
            emailTextBox.TextChanged += SettingsChanged;
            passwordTextBox.TextChanged += SettingsChanged;            
        }

        private void SettingsChanged(object sender, EventArgs e)
        {
            string name = ((Control)sender).Name;

            if (name == "emailTextBox")
            {
                AppSettings.Email = MailBox.Email = emailTextBox.Text.ToLower();
            }
            else if (name == "passwordTextBox")
            {
                AppSettings.Password = MailBox.Password = passwordTextBox.Text;                
            }              

            MailBoxTimer.Init(timer);
        }

        private void HideOrShowForm()
        {
            if (Visible)
            {
                Hide();                
            }
            else
            {
                Show();
                WindowState = FormWindowState.Normal;
                CenterToScreen();
            }
        }

        private void SettingsMenuItemClick(object sender, EventArgs e)
        {
            HideOrShowForm();
        }        

        private void ExitMenuItemClick(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void NotifyIconMouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                HideOrShowForm();
            }            
        }       
       
        private void AppFormFormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                HideOrShowForm();
            }              
        }                 
    }
}
